package com.rw.coco.handler.message.reply.handler.validate;

import com.rw.coco.api.data.CacheMapper;
import com.rw.coco.handler.message.event.CocoGroupMessageEvent;
import com.rw.coco.handler.message.reply.GroupReplyHandler;
import com.rw.coco.handler.message.reply.util.FrequencyUtil;
import com.rw.coco.util.CocoReplyUtil;
import com.rw.tool.util.string.StringFormatter;

import java.text.MessageFormat;

/**
 * 群聊频率限制器
 */
public class GroupFrequencyHandler extends GroupReplyHandler {
    @Override
    protected boolean groupTrigger(CocoGroupMessageEvent groupEvent) {
        // 获取频率token
        final String frequencyTokenTemplate = "com.rw.coco.frequency.group.{}";
        long groupId = groupEvent.getGroupModel().getGroupId();
        String frequencyToken = StringFormatter.format(frequencyTokenTemplate, groupId);

        // 判断频率是否超频
        CacheMapper cacheMapper = groupEvent.getCacheMapper();
        // 如果超频，则拦截
        return FrequencyUtil.countGroupFreq(frequencyToken, cacheMapper);
    }

    @Override
    protected void groupHandler(CocoGroupMessageEvent groupEvent) {
        // 获取警告token
        final String warnTokenTemplate = "com.rw.coco.warn.group.{}";
        long groupId = groupEvent.getGroupModel().getGroupId();
        String warnToken = StringFormatter.format(warnTokenTemplate, groupId);

        // 判断警告是否超频
        CacheMapper cacheMapper = groupEvent.getCacheMapper();
        int warnExceeded = FrequencyUtil.warn(warnToken, cacheMapper);
        String groupName = groupEvent.getGroup().getName();
        // 如果未超频则正常警告
        if (warnExceeded < FrequencyUtil.maxWarnCount) {
            // 回复警告对话
            String replyTemplate = CocoReplyUtil.REPLY_PROP.get(CocoReplyUtil.GROUP_FREQ_EXCEEDED);
            String reply = MessageFormat.format(replyTemplate, warnExceeded);
            groupEvent.sendBack(reply);

            // 输出日志
            final String logTemplate = "群 {}({}) 对话超频，警告 {} 次";
            String log = StringFormatter.format(logTemplate, groupId, groupName, warnExceeded);
            groupEvent.getCocoLogger().info(log);
        } else {
            // 如果警告次数超过限制，回复退群信息
            String reply = CocoReplyUtil.REPLY_PROP.get(CocoReplyUtil.GROUP_WARN_EXCEEDED);
            groupEvent.sendBack(reply);

            // 退群，拉黑
            groupEvent.quit();
            groupEvent.getPersistenceMapper().blackGroup(groupId);

            // 输出日志
            final String logTemplate = "群 {}({}) 对话超频，警告无效，已退群拉黑处理";
            String log = StringFormatter.format(logTemplate, groupId, groupName);
            groupEvent.getCocoLogger().info(log);

            // 清除缓存
            cacheMapper.delete(warnToken);
        }
    }
}
